from flask import render_template, redirect, url_for
from .forms import PostTopicForm, CommentForm
from . import bp
from .. import db
from flask.ext.login import current_user, login_required
from ..models import Post, Comment
from hashlib import md5
from ..helpers import gravatar_url, admin_required
import mistune

markdown = mistune.Markdown()

@bp.route('/', methods=['GET', 'POST'])
def index():
    posts = Post.query.order_by(Post.post_time.desc())
    return render_template('main/index.html', posts=posts)

@bp.route('/post-topic', methods=['GET', 'POST'])
@login_required
def post_topic():
    form = PostTopicForm()
    if form.validate_on_submit():
        avatar_url = gravatar_url(current_user.email, 40)
        post = Post(title=form.title.data,
                    body=form.body.data,
                    body_md=markdown(form.body.data),
                    username=current_user.username,
                    avatar = avatar_url)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('main.index'))
    return render_template('main/post-topic.html', form=form)

@bp.route('/topic/<int:id>', methods=['GET', 'POST'])
def topic(id):
    form = CommentForm()
    if form.validate_on_submit():
        avatar_url = gravatar_url(current_user.email, 40)
        comment = Comment(topic_id=id,
                          comment=form.comment.data,
                          username=current_user.username,
                          avatar=avatar_url)
        db.session.add(comment)
        db.session.commit()
        return redirect('/topic/'+str(id))
    topic = Post.query.get_or_404(id)
    comments = Comment.query.filter_by(topic_id=id).order_by(Comment.comment_time)
    return render_template('main/topic.html', topic=topic, form=form, comments=comments)

@bp.route('/delete/<int:id>', methods=['GET', 'POST'])
@admin_required
def delete(id):
    posts = Post.query.get_or_404(id)
    comments = Comment.query.filter_by(topic_id=id).all()
    db.session.delete(posts)
    for comment in comments:
        db.session.delete(comment)
    db.session.commit()
    return redirect(url_for('main.index'))
